package com.danskin.wechat.webapi;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.jeewx.api.core.exception.WexinReqException;
import org.jeewx.api.third.JwThirdAPI;
import org.jeewx.api.third.model.ApiComponentToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.fastjson.JSONObject;
import com.danskin.wechat.api.client.WeiXinOpenApiClient;
import com.danskin.wechat.entity.WxAuthTicket;
import com.danskin.wechat.entity.WxMediaPlatform;
import com.danskin.wechat.service.SysAreaService;
import com.danskin.wechat.service.WechatOpService;
import com.danskin.wechat.util.DateTools;
import com.danskin.wechat.util.LogUtil;
import com.danskin.wechat.util.Page;

public class BaseApiController {

	public final static Logger logger = Logger.getLogger(BaseApiController.class);

	/**
	 * 微信全网发布账号
	 */
	@Value("${component_appid}")
	protected String COMPONENT_APPID;
	@Value("${component_appsecret}")
	protected String COMPONENT_APPSECRET;
	@Value("${component_encoding_aeskey}")
	protected String COMPONENT_ENCODINGAESKEY;
	@Value("${component_token}")
	protected String COMPONENT_TOKEN;

	// protected final static String COMPONENT_APPID = "wx6088cabc0a099afc";
	// protected final static String COMPONENT_APPSECRET =
	// "fb6478bb1022aa27a47b92619632b5e9";
	// protected final static String COMPONENT_ENCODINGAESKEY =
	// "FAS234SFA56SFDSASDFD4554387FAKJNMHY89745KJH";
	// protected final static String COMPONENT_TOKEN = "WeLink";

	@Autowired
	public WechatOpService wechatOpService;

	@Autowired
	public SysAreaService areaService;

	// protected Map<String, String> VipLevel = new HashMap<String, String>();

	public BaseApiController() {
		// VipLevel.put("v0", "-");
		// VipLevel.put("v1", "新锐会员");
		// VipLevel.put("v2", "菁英会员");
		// VipLevel.put("v3", "铜牌会员");
		// VipLevel.put("v4", "银牌会员");
		// VipLevel.put("v5", "金牌会员");
		// VipLevel.put("v6", "韦德会员");
	}

	/**
	 * 获取第三方平台ACCESS_TOKEN
	 * 
	 * @author Allen Liu
	 * @return String
	 * @throws WexinReqException
	 */
	protected String getComponentAccessToken() throws WexinReqException {

		WxAuthTicket entity = wechatOpService.getAuthTicket(COMPONENT_APPID);
		if (entity != null) {
			Date now = new Date();
			if (entity.getAccessToken() == null || now.getTime() > entity.getAccessTokenExpires().getTime()) { // 过期将重取
				ApiComponentToken apiComponentToken = new ApiComponentToken();
				apiComponentToken.setComponent_appid(COMPONENT_APPID);
				apiComponentToken.setComponent_appsecret(COMPONENT_APPSECRET);
				apiComponentToken.setComponent_verify_ticket(entity.getTicket());

				String component_access_token = JwThirdAPI.getAccessToken(apiComponentToken);
				// 更新access_token
				entity.setAccessToken(component_access_token);
				entity.setAccessTokenExpires(DateTools.getDateTools().operationHour(now, 2, true));
				wechatOpService.saveOrUpdateTicket(entity);

				return component_access_token;
			}

			return entity.getAccessToken();
		}

		return "";
	}

	/**
	 * 获取公众号ACCESS_TOKEN
	 * 
	 * @author Allen Liu
	 * @return String
	 * @throws WexinReqException
	 */
	protected String getMPAccessToken(String appId) {

		WxMediaPlatform entity = this.getMPWithAccessToken(appId);
		if (entity != null) {
			return entity.getAccessToken();
		}

		return "";
	}

	/**
	 * 获取mpId
	 * 
	 * @param appId
	 * @return
	 * @author makunsmac
	 */
	protected Integer getMpId(String appId) {
		// LogUtil.info("======获取mpId参数：appId=" + appId);
		Integer mpId = 0;
		try {
			WxMediaPlatform entity = wechatOpService.queryMediaPlatformByAppId(appId);
			if (entity != null) {
				mpId = entity.getId();
			}
		} catch (Exception e) {
			LogUtil.error("=====获取mpId异常", e);
		}
		return mpId;
	}

	/**
	 * 获取公众号信息
	 * 
	 * @param appId
	 * @return
	 */
	protected WxMediaPlatform getMediaPlatform(String appId) {
		return wechatOpService.queryMediaPlatformByAppId(appId);
	}

	/**
	 * 获取公众号信息
	 * 
	 * @param mpId
	 * @return
	 */
	protected WxMediaPlatform getMPWithAccessToken(String appId) {

		WxMediaPlatform entity = wechatOpService.queryMediaPlatformByAppId(appId);
		if (entity != null) {
			Date now = new Date();
			if (entity.getAccessToken() == null || now.getTime() > entity.getAccessTokenExpires().getTime()) { // 过期将重取

				String component_access_token;
				try {
					component_access_token = this.getComponentAccessToken();

					JSONObject json = WeiXinOpenApiClient.createInstance().getAuthorizerToken(component_access_token,
							COMPONENT_APPID, entity.getAppId(), entity.getRefreshToken());

					if (json != null) {
						String authorizer_access_token = json.getString("authorizer_access_token");
						// 更新access_token
						entity.setAccessToken(authorizer_access_token);
						entity.setRefreshToken(json.getString("authorizer_refresh_token"));
						entity.setAccessTokenExpires(
								DateTools.getDateTools().operationSecond(now, json.getInteger("expires_in")));
						// 更新至数据库
						wechatOpService.saveWxMediaPlatform(entity);

						return entity;
					}
					return null;

				} catch (WexinReqException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
			}

			return entity;
		}

		return null;
	}

	protected WxMediaPlatform getMP(int mpId) {

		WxMediaPlatform entity = wechatOpService.queryMediaPlatform(mpId);
		return entity;
	}

	/**
	 * 获取公众号信息
	 * 
	 * @param mpId
	 * @return
	 */
	protected WxMediaPlatform getMPWithAccessToken(int mpId) {

		WxMediaPlatform entity = wechatOpService.queryMediaPlatform(mpId);
		if (entity != null) {
			Date now = new Date();
			if (entity.getAccessToken() == null || now.getTime() > entity.getAccessTokenExpires().getTime()) { // 过期将重取

				String component_access_token;
				try {
					component_access_token = this.getComponentAccessToken();

					JSONObject json = WeiXinOpenApiClient.createInstance().getAuthorizerToken(component_access_token,
							COMPONENT_APPID, entity.getAppId(), entity.getRefreshToken());

					if (json != null) {
						String authorizer_access_token = json.getString("authorizer_access_token");
						// 更新access_token
						entity.setAccessToken(authorizer_access_token);
						entity.setRefreshToken(json.getString("authorizer_refresh_token"));
						entity.setAccessTokenExpires(
								DateTools.getDateTools().operationSecond(now, json.getInteger("expires_in")));
						// 更新至数据库
						wechatOpService.saveWxMediaPlatform(entity);

						return entity;
					}
					return null;

				} catch (WexinReqException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
			}

			return entity;
		}

		return null;
	}

	/**
	 * 获取微信公众号JsApiTicket
	 * 
	 * @param appId
	 * @return
	 */
	protected String getJsApiTicket(String appId) {

		WxMediaPlatform entity = this.getMPWithAccessToken(appId);// wechatOpService.queryMediaPlatformByAppId(appId);
		if (entity != null) {
			Date now = new Date();
			if (entity.getJsapiTicket() == null || now.getTime() > entity.getJsapiTicketExpires().getTime()) { // 过期将重取

				String access_token = entity.getAccessToken();// this.getMPAccessToken(appId);

				JSONObject json = WeiXinOpenApiClient.createInstance().getTicket(access_token, "jsapi");

				if (json != null) {
					String ticket = json.getString("ticket");
					// 更新access_token
					entity.setJsapiTicket(ticket);
					entity.setJsapiTicketExpires(
							DateTools.getDateTools().operationSecond(now, json.getInteger("expires_in")));
					// 更新至数据库
					wechatOpService.saveWxMediaPlatform(entity);

					return ticket;
				}
				return "";
			}

			return entity.getJsapiTicket();
		}

		return "";
	}

	protected String getCardApiTicket(String appId) {

		WxMediaPlatform entity = this.getMPWithAccessToken(appId);// wechatOpService.queryMediaPlatformByAppId(appId);
		if (entity != null) {
			Date now = new Date();
			if (entity.getCardApiTicket() == null || now.getTime() > entity.getCardApiTicketExpires().getTime()) { // 过期将重取

				String access_token = entity.getAccessToken();// this.getMPAccessToken(appId);

				JSONObject json = WeiXinOpenApiClient.createInstance().getTicket(access_token, "wx_card");

				if (json != null) {
					String ticket = json.getString("ticket");
					// 更新access_token
					entity.setCardApiTicket(ticket);
					entity.setCardApiTicketExpires(
							DateTools.getDateTools().operationSecond(now, json.getInteger("expires_in")));
					// 更新至数据库
					wechatOpService.saveWxMediaPlatform(entity);

					return ticket;
				}
				return "";
			}

			return entity.getCardApiTicket();
		}

		return "";
	}

	protected JSONObject getError(String errMsg) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("errorCode", "-1");
		jsonObject.put("errorMsg", errMsg);
		return jsonObject;
	}

	/**
	 * 判断参数是否有效
	 * 
	 * @param key
	 * @param map
	 * @return
	 */
	protected boolean isValid(String key, Map<String, Object> map) {

		return map.containsKey(key) && map.get(key) != null && !map.get(key).toString().equals("");
	}

	protected String getMapValue(String key, Map<String, Object> map) {
		if (map.containsKey(key)) {
			Object obj = map.get(key);
			if (obj != null) {
				return map.get(key).toString();
			}
		}
		return null;
	}

	protected boolean isValid(String key, JSONObject json) {

		return json.containsKey(key) && json.get(key) != null && !json.get(key).toString().equals("");
	}

	protected String getJSONValue(String key, JSONObject json) {
		if (json.containsKey(key)) {
			Object obj = json.get(key);
			if (obj != null) {
				return json.get(key).toString();
			}
		}
		return null;
	}

	public Map getRequestParameter(HttpServletRequest request) throws UnsupportedEncodingException {
		Map properties = request.getParameterMap();
		Map returnMap = new HashMap();
		Iterator entries = properties.entrySet().iterator();
		Map.Entry entry;
		String name = "";
		String value = "";
		while (entries.hasNext()) {
			entry = (Map.Entry) entries.next();
			name = (String) entry.getKey();
			Object valueObj = entry.getValue();
			if (null == valueObj) {
				value = "";
			} else if (valueObj instanceof String[]) {

				String[] values = (String[]) valueObj;
				for (int i = 0; i < values.length; i++) {
					value = values[i] + ",";
				}
				value = value.substring(0, value.length() - 1);
			} else {
				value = valueObj.toString();
			}
			value = new String(value.getBytes("iso-8859-1"), "UTF-8");
			returnMap.put(name, value);
		}
		return returnMap;
	}

	public Object pagelistToJSONForBootStrapTable(List<?> pdList, Page page) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (null != pdList) {
			if (null != page) {
				map.put("total", page.getTotalResult());
			}
			map.put("rows", pdList);
		} else {
			map.put("rows", null);
		}
		return map;
	}
}
